package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.service.ApArticleConfigService;
import com.heima.common.constants.message.ArticleForEsConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApArticleConfigServiceImpl extends ServiceImpl<ApArticleConfigMapper, ApArticleConfig> implements ApArticleConfigService {
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 修改文章上下架
     */
    @Override
    public ResponseResult downOrUpArticle(Integer articleId, Boolean enable) {
        //判断数据是否合法
        if (articleId == null || enable == null) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询数据库中是否存在此文章的配置
        LambdaQueryWrapper<ApArticleConfig> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ApArticleConfig::getArticleId, articleId);
        ApArticleConfig one = getOne(wrapper);
        if (one == null) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //封装修改数据
        one.setIsDown(enable);
        updateById(one);
        //发消息通知es更新索引库中的文档
        Map map = new HashMap<>();
        map.put("articleId", articleId);
        if (!enable) {
            kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_DELETE, JSON.toJSONString(map));
        } else {
            kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_ADD, JSON.toJSONString(map));
        }
        return ResponseResult.okResult();
    }
}
